<template>
    <div class="addproductcategary">
        <el-form :model="ruleForm" label-width="150px" :rules="rules" ref="ruleFormRef">
            <el-form-item label="分类名称：" prop="name">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="上级分类：" prop="parentId">
                <el-select v-model="ruleForm.parentId" placeholder="请选择">
                    <el-option v-for="item in parentLevels" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="数量单位：" prop="productUnit">
                <el-input v-model="ruleForm.productUnit" />
            </el-form-item>
            <el-form-item label="排序：" prop="sort">
                <el-input v-model="ruleForm.sort" />
            </el-form-item>
            <el-form-item label="是否显示：" prop="showStatus">
                <el-radio-group v-model="ruleForm.showStatus">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否显示在导航栏：" prop="navStatus">
                <el-radio-group v-model="ruleForm.navStatus">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="分类图标：">
                <el-upload ref="upload" class="upload-demo" action="http://120.24.64.5:8088/mall-admin/minio/upload"
                    :limit="1" :on-exceed="handleExceed" list-type="picture" :before-upload="beforeAvatarUpload"
                    :file-list="fileList" :on-success="handleAvatarSuccess" :on-remove="handleRemove">
                    <template #trigger>
                        <el-button type="primary">点击上传</el-button>
                    </template>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传jpg/png文件，且不超过100kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item label="筛选属性：" prop="productAttributeIdList" class="select-attr">
                <div v-for="el in selectArr" :key="el.id" class="attr-item">
                    <el-select v-model="el.attrId" placeholder="请选择" @change="changeFn">
                        <el-option v-for="item in attr" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                    <el-button type="default" @click="delAttrFn(el.id)">删除</el-button>
                </div>
                <el-button type="primary" @click="toAddAttrFn">新增</el-button>
            </el-form-item>
            <el-form-item label="关键词：" prop="keywords">
                <el-input v-model="ruleForm.keywords" />
            </el-form-item>
            <el-form-item label="分类描述：" prop="description">
                <el-input v-model="ruleForm.description" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                <el-button type="default" @click="resetForm(ruleFormRef)" v-show="!route.query.id">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules, genFileId, UploadFile, UploadFiles, UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { pro } from '@/api'
import { useTable } from '@/hooks/useTable'
import { useRoute, useRouter } from 'vue-router';

const route = useRoute()
const router = useRouter()
interface ILevel {
    id: number,
    name: string
}
interface ISelectArr {
    id: number,
    attrId: number
}
const state = reactive<{ ruleForm: IAddProductCategory, parentLevels: ILevel[], attr: ILevel[], selectArr: ISelectArr[] }>({
    ruleForm: {
        description: '',
        icon: '',
        keywords: '',
        name: '',
        navStatus: 0,
        parentId: 0,
        productUnit: '',
        showStatus: 0,
        sort: 0,
        productAttributeIdList: []
    },
    parentLevels: [],//处理一级分类
    attr: [],//处理筛选属性的显示
    selectArr: [{ id: 1, attrId: 0 }]//处理筛选属性是否选中
})
//上传文件
const upload = ref<UploadInstance>()
const fileList = ref<UploadUserFile[]>([])
let { ruleForm, parentLevels, attr, selectArr } = toRefs(state);
const ruleFormRef = ref<FormInstance>()
const params = reactive({
    parentId: 0,
    pageSize: 100
})
if (route.query.id) {
    pro.getIDCategoryApi(parseInt(route.query.id as string)).then(res => {
        if (res.code === 200) {
            state.ruleForm = res.data;
            if (res.data.icon) {
                fileList.value = [{ name: res.data.icon.substr((res.data.icon.lastIndexOf("/")) + 1), url: res.data.icon }]
            }
        }
    })
}
Promise.all([
    useTable(pro.queryProductCategoryListApi, params),
    pro.getProductCategoryAttrApi(),
]).then(([res1, res2,]) => {
    if (res1.tableData && res2.code === 200) {
        state.parentLevels = res1.tableData.value.map((item) => ({ id: item.id, name: item.name }));
        state.parentLevels.unshift({ id: 0, name: '无上级分类' })
        state.attr = res2.data.map(item => ({ id: item.id, name: item.name }))
    }
})

// 新增
let id = state.selectArr[(state.selectArr.length) - 1].id
const toAddAttrFn = () => {
    state.selectArr.push({ id: id, attrId: 0 })
}
// 删除
const delAttrFn = (id: number) => {
    let idx = state.selectArr.findIndex(item => item.id === id)
    state.ruleForm.productAttributeIdList.forEach((item, index) => {
        if (item === state.selectArr[idx].attrId) {
            state.ruleForm.productAttributeIdList.splice(index, 1)
        }
    })
    state.selectArr.splice(idx, 1)
}
// 属性select的change
const changeFn = (val: number) => {
    if (state.ruleForm.productAttributeIdList.indexOf(val) === -1) {
        state.ruleForm.productAttributeIdList.push(val)
    }
}
// 校验
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
    ],
})
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 发请求
            ElMessageBox.confirm(
                '确定要提交数据吗？', '提示',
            ).then(() => {
                if (route.query.id) {
                    pro.editIDCategoryApi({ id: Number(route.query.id), productCategoryParam: state.ruleForm }).then(res => {
                        if (res.code === 200) {
                            ElMessage.success('提交成功');
                            formEl.resetFields()
                            router.push('/pms/productCate')
                        }
                    })
                } else {
                    pro.createProductCategoryApi(state.ruleForm).then(res => {
                        if (res.code === 200) {
                            ElMessage.success('提交成功')
                            formEl.resetFields()
                            useTable(pro.queryProductCategoryListApi, params)
                        }
                    })
                }

            })

        } else {
            return false
        }
    })
}
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 个数限制
const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}
// :auto-upload="false"
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('只能上传.jpg或.png格式的 文件！')
        return false
    } else if (rawFile.size / 1024 > 100) {
        ElMessage.error('上传的图片不能超过100K!')
        return false
    }
    return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
    console.log('response', response);
    console.log('uploadFile', uploadFile);
    console.log('uploadFiles', uploadFiles);
    fileList.value.push(response.data)
    state.ruleForm.icon = response.data.url
    // let url = uploadFile.url?.slice(0, uploadFile.url.lastIndexOf("/") + 1).replace("blob:", "") + uploadFile.name;
    // console.log('url', url);
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    state.ruleForm.icon = ''
}
</script>

<style scoped lang="less">
.addproductcategary {
    border: 1px solid #ebeef5;
    padding: 50px 100px;
    margin: 20px;
}

.select-attr {
    width: 500px;
    display: flex;
    flex-wrap: wrap;
}

.attr-item {
    margin: 20px 0;

    .el-button {
        margin-left: 20px;
    }
}
</style>